package com.work.task.utils;

import ch.ethz.ssh2.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class GanymedUtils {

    private static final Logger logger = LoggerFactory.getLogger(GanymedUtils.class);

    /** 超时时间 */
    private static final int TIME_OUT = 1000 * 5 * 60;

    /**
     * 登录远端服务器
     *
     * @param ip       主机地址
     * @param userName 用户名
     * @param password 密码
     * @return 当前的连接
     * @throws IOException
     */
    public static Connection login(String ip, String userName, String password) throws IOException {
        Connection connection = new Connection(ip);
        connection.connect();
        return connection.authenticateWithPassword(userName, password) ? connection : null;
    }

    /**
     * 执行一个命令
     *
     * @param ip       主机ip
     * @param userName 用户名
     * @param password 密码
     * @param scripts  需要执行的脚本
     * @param charset  字符编码
     * @return ShellResult类
     * @throws Exception
     */
    public static ShellResult exec(String ip, String userName, String password, String scripts, Charset charset) throws IOException {

        Connection connection = login(ip, userName, password);
        if (connection == null) {
            throw new RuntimeException("登录远程服务器出现异常,ip为:" + ip);
        }

        // Open a new {@link Session} on this connection
        Session session = connection.openSession();

        try (InputStream stdOut = new StreamGobbler(session.getStdout()); InputStream stdErr = new StreamGobbler(session.getStderr())) {
            // Execute a command on the remote machine.
            session.execCommand(scripts);
            String outStr = processStream(stdOut, charset.name());
            String outErr = processStream(stdErr, charset.name());
            session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
            int exitStatus = session.getExitStatus();
            return new ShellResult(outStr, outErr, exitStatus);
        }
    }

    /**
     * 执行脚本
     *
     * @param in      输入流
     * @param charset 字符编码
     * @return
     * @throws IOException
     */
    private static String processStream(InputStream in, String charset) throws IOException {
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while (in.read(buf) != -1) {
            sb.append(new String(buf, charset));
        }
        return sb.toString();
    }

    public static void main(String[] args) {

        /** 执行命令
        try {
            ShellResult status = exec("106.55.246.129", "root", "Kingboyrang@soft8275", "ifconfig", StandardCharsets.UTF_8);
            System.out.println(">>>>>>Result>>>>>>>");
            System.out.println(status.getResult());
            System.out.println(">>>>>>ErrorMsg>>>>>>>>");
            System.out.println(status.getErrorMsg());
        } catch (IOException e) {
            e.printStackTrace();
        }
         **/

        //下载文件
        downloadFile("120.25.56.234","wulanzhou","Wlz@2018","ROOT.war","/home/wulanzhou/","/Users/wulanzhou/Desktop/file/");
        //downloadFile("106.55.246.129","root","Kingboyrang@soft8275","redis.tar.gz","/data/soft/","/Users/wulanzhou/Desktop/file/");

        //上传文件
        //uploadFile("106.55.246.129","root","Kingboyrang@soft8275","/Users/wulanzhou/Desktop/newpool.txt","/root/");

        //执行shell脚本
        //runSSHFile("106.55.246.129","root","Kingboyrang@soft8275","/root/aa.sh");
        //执行python脚本
        //runSSHFile("14.215.135.16","wulanzhou","Wulanzhou@123","/root/aa.sh");


    }


    /**
     *  其他服务器下载文件
     * @param host
     * @param username
     * @param password
     * @param remoteFile            服务器上的文件名
     * @param remoteTargetDirectory 服务器上文件的所在路径
     * @param newPath               下载文件的路径
     */
    public static void downloadFile(String host, String username, String password,
                                    String remoteFile, String remoteTargetDirectory,String newPath)  {
        try {
            logger.info("spc [" + remoteFile + "] from " + host + " to "
                    + newPath);
            Connection conn = login(host, username, password);
            if (conn==null){
                logger.error("连接失败");
                return;
            }
            SCPClient client = new SCPClient(conn);
            SCPInputStream sis = client.get(remoteTargetDirectory + "/" + remoteFile);
            File f = new File(newPath);
            if(!f.exists()){
                f.mkdirs();
            }
            File newFile = new File(newPath + remoteFile);
            FileOutputStream fos = new FileOutputStream(newFile);
            byte[] b = new byte[4096];
            int i;
            while ((i = sis.read(b)) != -1){
                fos.write(b,0, i);
            }
            fos.flush();
            fos.close();
            sis.close();
            conn.close();
            logger.info("download ok");


        }catch (IOException ex){
            ex.printStackTrace();
        }

    }

    /**
     * (上传文件到服务器)将文件拷贝到其他计算机上
     * @param host
     * @param username
     * @param password
     * @param uploadFilePath (本地文件)
     * @param remoteDir
     * @throws IOException
     */
    public static void uploadFile(String host, String username, String password,
                              String uploadFilePath, String remoteDir)  {

        try {

            logger.info("spc [" + uploadFilePath + "] to " + host + remoteDir);

            Connection conn = login(host, username, password);
            if (conn == null){
                logger.error("连接失败");
                return;
            }

            File f = new File(uploadFilePath);

            SCPClient client = new SCPClient(conn);
            SCPOutputStream os = client.put(f.getName(),f.length(), remoteDir,null);
            byte[] b = new byte[4096];
            FileInputStream fis = new FileInputStream(f);
            int i;
            while ((i = fis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
            fis.close();
            os.close();
            conn.close();
            logger.info("upload ok");

        }catch (IOException ex){
             ex.printStackTrace();
        }

    }

    /**
     *  获取服务器上相应文件的流
     * @param remoteFile 文件名
     * @param remoteTargetDirectory 文件路径
     * @return
     * @throws IOException
     */
    public SCPInputStream getStream(String host,int port,String username, String password,String remoteFile, String remoteTargetDirectory) throws IOException {
        Connection connection = new Connection(host,port);
        connection.connect();
        boolean isAuthenticated = connection.authenticateWithPassword(username,password);
        if(!isAuthenticated){
            System.out.println("连接建立失败");
            return null;
        }
        SCPClient scpClient = connection.createSCPClient();
        return scpClient.get(remoteTargetDirectory + "/" + remoteFile);
    }

    //执行SSH命令.
    public static int runSSH(String host, String username, String password,
                             String cmd) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("running SSH cmd [" + cmd + "]");
        }
        Connection conn = login(host, username, password);
        Session sess = conn.openSession();
        sess.execCommand(cmd);
        InputStream stdout = new StreamGobbler(sess.getStdout());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            if (logger.isDebugEnabled()) {
                logger.debug(line);
            }
        }
        sess.close();
        conn.close();
        return sess.getExitStatus().intValue();
    }

    //执行ssh脚本
    public static int runSSHFile(String host, String username, String password,
                                  String sshFilePath){
        int ret = -1;
        try {
            Connection conn = login(host, username, password);
            Session session = conn.openSession();
            session.execCommand(sshFilePath);

            InputStream stdout = new StreamGobbler(session.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            while (true) {
                String line = br.readLine();
                if (line == null)
                    break;
                if (logger.isDebugEnabled()) {
                    logger.debug(line);
                }
            }
            session.close();
            conn.close();

            ret = session.getExitStatus().intValue();
            //session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
            //ret = session.getExitStatus();

            //conn.close();

        }catch (IOException ex){
            ex.printStackTrace();
        }

        return ret;

    }

    //执行本地的cmd命令.(DOS命令)
    public static int runLocal(String cmd) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("running local cmd [" + cmd + "]");
        }
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec(cmd);
        InputStream stdout = new StreamGobbler(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            if (logger.isDebugEnabled()) {
                logger.debug(line);
            }
        }
        return p.exitValue();
    }
}
